package tools;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;

public class GNUPLOT 
{
	public static void draw(String content,String x,String outputfile,boolean pause) throws IOException, InterruptedException
	{
		String firstline=content.substring(0,content.indexOf('\n'));
		ArrayList<String> columns=new ArrayList<String>();
		StringTokenizer st=new StringTokenizer(firstline);
		while(st.hasMoreElements())
		{
			columns.add(st.nextToken());
		}
		
		//Write gnuplot file
		PrintWriter ecrivain =  new PrintWriter(new BufferedWriter(new FileWriter(outputfile+".data")));
		ecrivain.write(content.substring(content.indexOf('\n')+1));
		ecrivain.close();

		ecrivain =  new PrintWriter(new BufferedWriter(new FileWriter(outputfile+".gnuplot")));
		ecrivain.println("set data style linespoints;");
		ecrivain.print("plot ");
		int xi=columns.indexOf(x);
		boolean f=false;
		for(int i=0;i<columns.size();i++)
		{
			if (i==xi) continue;
			if (f) ecrivain.print(",");
			f=true;
			ecrivain.print("\""+outputfile+".data\" using "+(xi+1)+":"+(i+1)+" title \""+columns.get(i)+"\"");
		}
		ecrivain.println(";");
		if (pause) ecrivain.println("pause "+-1+";");
		ecrivain.println("set title \""+outputfile+"\"");
		ecrivain.close();
		
		Runtime.getRuntime().exec("gnuplot "+outputfile+".gnuplot");
	}
}
